'''
Author: duliang thinktanker@163.com
Date: 2024-02-02 15:50:12
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-02-02 22:35:59
FilePath: \spot-the-differences-\spot.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
import win32gui, win32ui, win32con
import pyautogui
from PIL import ImageTk
import PIL.Image
import os
import cv2
import time
# import sys
# from itertools import cycle
from threading import Thread
from tkinter import *

left = 0
top = 0
right = 0
bottom = 0


def snapshot(className=None, winName=None):
    '''
    可以后台截屏，但不能最小化窗口
    '''
    global left
    global top
    global right
    global bottom
    while 1:
        #获取后台窗口的句柄，注意后台窗口不能最小化
        hWnd = win32gui.FindWindow(className,
                                   winName)  #窗口的类名可以用Visual Studio的SPY++工具获取
        if hWnd:
            #获取句柄窗口的大小信息
            left, top, right, bottom = win32gui.GetWindowRect(hWnd)

            # 输出坐标信息
            # print('窗口左上角坐标：({}, {})'.format(left, top))
            # print('窗口右下角坐标：({}, {})'.format(right, bottom))

            width = right - left
            height = bottom - top
            #返回句柄窗口的设备环境，覆盖整个窗口，包括非客户区，标题栏，菜单，边框
            hWndDC = win32gui.GetWindowDC(hWnd)
            # while 1:
            #创建设备描述表
            mfcDC = win32ui.CreateDCFromHandle(hWndDC)
            #创建内存设备描述表
            saveDC = mfcDC.CreateCompatibleDC()
            #创建位图对象准备保存图片
            saveBitMap = win32ui.CreateBitmap()
            #为bitmap开辟存储空间
            saveBitMap.CreateCompatibleBitmap(mfcDC, width, height)
            #将截图保存到saveBitMap中
            saveDC.SelectObject(saveBitMap)
            #保存bitmap到内存设备描述表
            saveDC.BitBlt((0, 0), (width, height), mfcDC, (0, 0),
                          win32con.SRCCOPY)
            ###获取位图信息
            bmpinfo = saveBitMap.GetInfo()
            bmpstr = saveBitMap.GetBitmapBits(True)
            # saveBitMap.SaveBitmapFile(saveDC, './pil.jpg')
            #内存释放
            win32gui.DeleteObject(saveBitMap.GetHandle())
            saveDC.DeleteDC()
            mfcDC.DeleteDC()
            win32gui.ReleaseDC(hWnd, hWndDC)
            ###生成图像

            im_PIL = PIL.Image.frombuffer(
                'RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr,
                'raw', 'BGRX', 0, 1)
            box1 = (95, 310, 475, 600)
            crop1 = im_PIL.crop(box1)
            box2 = (550, 310, 930, 600)
            crop2 = im_PIL.crop(box2)
            try:
                crop1.save('./img/c1.jpg')
                crop2.save('./img/c2.jpg')
            except Exception as e:
                print(e)
            time.sleep(1)


def on_rect_click(event):
    print("矩形被点击了！")


def get_mouse_pos(event):
    x, y = event.widget.winfo_pointerxy()
    print(event.x, event.y)
    pyautogui.moveTo(left + event.x + 95, top + event.y + 310)
    pyautogui.click()
    pyautogui.moveTo(x, y)


if __name__ == "__main__":
    th1 = Thread(target=snapshot, args=('#32770', '大家来找茬'), daemon=True)
    th1.start()
    num = 0
    tk = Tk()
    canvas = Canvas(tk, width=380, height=290)
    tk.bind('<Button-1>', get_mouse_pos)
    while 1:
        num += 1
        if num > 2:
            num = 1
        filename = f'./img/c{num}.jpg'
        if os.path.isfile(filename):
            img1 = cv2.imread(filename)
            try:
                im1 = PIL.Image.fromarray(cv2.cvtColor(img1,
                                                       cv2.COLOR_BGR2RGB))
                img = ImageTk.PhotoImage(image=im1)
                itext = canvas.create_image(0, 0, anchor='nw', image=img)
                canvas.pack()
                tk.update()
                tk.after(200)
            except Exception as e:
                print(e)
                if "Too" in str(e):
                    break
